<script setup>
import { onMounted, ref } from "vue";
import luckysheet from "luckysheet";
import LuckyExcel from "luckyexcel";
import { useAnalysetStore } from "@/store/index.ts";
import AnalyesAPI from "@/api/system/analyes.ts";
import dayjs from "dayjs";
import {
  getHeaders,
  splitDataIntoPages,
  filterValidSampleAdatas,
  filterValidSamples,
  processTableData,
} from "@/utils/method";
import Device from "@/components/analysisSheetComponents/component/Device.vue";
import Index from "@/components/analysisSheetComponents/component/index.vue";
import indexPdf from "@/components/analysisSheetComponents/soil/tmpl82/indexPdf.vue";
let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: "zh",
  autoCalculate: true,
  data: [
    {
      row: 9,
      celldata: [
        // 初始化表格数据，第一行包含表头
        { r: 0, c: 0, v: "样品编号" }, // A1
        { r: 0, c: 1, v: "类型" }, // B1
        { r: 0, c: 2, v: "取样量(g)" }, // B1
        { r: 0, c: 3, v: "浸提剂体积V(mL)" }, // B1
        { r: 0, c: 4, v: "PH值" }, // B1
        { r: 0, c: 5, v: "测定结果" }, // B1
        { r: 0, c: 6, v: "备注" }, // B1
      ], // 初始化数据
      config: {
        merge: {}, // 合并单元格
        columnlen: {
          // 设置列宽
          0: 130, // 第一列宽度 150px
          1: 130, // 第二列宽度 120px
          2: 130, // 第三列宽度 180px
          3: 130, // 第四列宽度 100px
          4: 100, // 第五列宽度 200px
          5: 100, // 第六列宽度 150px
          6: 100, // 第六列宽度 150px
        }, // 表格列宽
      },
    },
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏dsadsadsadsadsadsa
};
const tableOption = ref([{ table: "仪器名称", id: 1 }]);
const waterForm = ref({
  pxycd: {},
  bzycd: {},
  notes: "",
  bzhcry: {},
  cdz: {},
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
});
const switchAB = ref(true);
const sheetData = ref("");
const jsonData = ref(null);
const checkTime = ref("");
const processedData = ref([]);
const checkDialogVisible = ref(false);
const analyseStatusPage = useAnalysetStore();
const record_sn = analyseStatusPage.waterForm.record_sn;
// pdf显示隐藏
const showTargetPage = ref(false);
const tableHeaders = ref([]);
const tabler = ref([]);
const switchAdd = ref(true);
// const cDatas = ref([]);
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  // 获取表单信息
  getWaterCapacity();
  // 复制粘贴
  getMethod();
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number; //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
    ? analyseStatusPage.waterForm.tableItem.test_method
    : analyseStatusPage.waterForm.tableItem.test_method_number; //分析方法
  waterForm.value.category_id =
    analyseStatusPage.waterForm.tableItem.sample_category; // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates;
};

// 保存新增表单
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map((row) => {
    return row
      .map((cell) => {
        return cell
          ? {
              field: cell.m || null,
              value: cell.v || null,
            }
          : null;
      })
      .filter((cell) => cell !== null); // 删除 null 值
  });

  processedData.value = filterValidSampleAdatas(processTableData(data));

  // waterForm.value.pxycd.averageTow = waterForm.value.pxycd.average;
  // waterForm.value.pxycd.differenceTow = waterForm.value.pxycd.difference;
  // waterForm.value.pxycd.allowedTow = waterForm.value.pxycd.allowed;
  // waterForm.value.pxycd.qualifiedTow = waterForm.value.pxycd.qualified;
  // waterForm.value.pxycd.averageFour = waterForm.value.pxycd.averageThree;
  // waterForm.value.pxycd.differenceFour = waterForm.value.pxycd.differenceThree;
  // waterForm.value.pxycd.allowedFour = waterForm.value.pxycd.allowedThree;
  // waterForm.value.pxycd.qualifiedFour = waterForm.value.pxycd.qualifiedThree;
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status;
    delete waterForm.value.reviewer_id;
  }

  console.log(waterForm.value, "waterForm.value");

  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 82,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    // cdatas: cDatas.value,
  }).then((data) => {
    // console.log("调接口拿数据", data);
    ElMessage.success("保存成功");
    getWaterCapacity();
    switchAdd.value = false;
  });
};

// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true;
};
const handleCheckClose = () => {
  checkDialogVisible.value = false;
};

const getWaterCapacity = () => {
  // console.log("");
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  };

  AnalyesAPI.getAnalyseACapacity(josn).then((data) => {
    // console.log("获取水质容量 A单", data);
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data;
      sheetData.value = data.configs;
      options.data = sheetData.value;
      luckysheet.create(options);
      processedData.value = data.adatas;

      waterForm.value.pxycd =
        Array.isArray(data.pxycd) && data.pxycd.length === 0 ? {} : data.pxycd;
      waterForm.value.bzhcry =
        Array.isArray(data.bzhcry) && data.bzhcry.length === 0
          ? {}
          : data.bzhcry;
      waterForm.value.bzycd =
        Array.isArray(data.bzycd) && data.bzycd.length === 0 ? {} : data.bzycd;
      console.log(waterForm.value, "waterForm.value ");
      // waterForm.value.bdatas =
      //   Array.isArray(data.bdatas) && data.bdatas.length === 0
      //     ? {}
      //     : data.bdatas;
      // waterForm.value.unit =
      //   Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      // waterForm.value.bdatas.pxycd =
      //   Array.isArray(data.bdatas?.pxycd) && data.bdatas.pxycd.length === 0
      //     ? {}
      //     : data.bdatas?.pxycd;
      // waterForm.value.bdatas.bzycd =
      //   Array.isArray(data.bdatas?.bzycd) && data.bdatas.bzycd.length === 0
      //     ? {}
      //     : data.bdatas.bzycd;

      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 22);
      tabler.value = getHeaders(data.adatas, 23);
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      };
    }
  });
};

const loadDataFromLocal = () => {
  const tableDataString = localStorage.getItem("tableData"); // 从 localStorage 获取存储的表格数据
  if (tableDataString) {
    console.log(tableDataString);
    options.data = JSON.parse(tableDataString); // 将字符串解析为 JSON
    console.log(options.data);
    const data = options.data[0].data.map((row) => {
      return row
        .map((cell) => {
          return cell
            ? {
                field: cell.m || "默认字段",
                value: cell.v || null,
              }
            : null;
        })
        .filter((cell) => cell !== null); // 删除 null 值
    });
    console.log(data);
    // 调用函数
    const processedData = processData(data);
    console.log("aghsduiahsuidhaiu", processedData);
    // 使用 Luckysheet API 回显数据
    luckysheet.create(options);
  } else {
    console.log("未找到本地存储的表格数据");
  }
};

// 剔除元素
const removeElementPrefix = (text) => {
  return text.replace(/^元素：\s*/, "");
};

// 剔除样品浓度ω( )
const extractBracketContent = (text) => {
  const match = text.match(/\((.*?)\)/);
  return match ? match[1] : text; // 如果匹配成功，返回括号内的内容，否则返回原文本
};

// 确认提交校核
const handleSubmit = () => {
  console.log(checkTime.value);
  const formattedDate = checkTime.value
    ? dayjs(checkTime.value).format("YYYY-MM-DD")
    : "";
  console.log(analyseStatusPage.waterForm.id);
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate,
  }).then((data) => {
    if (data === 1) {
      ElMessage.success("提交成功！");
      checkDialogVisible.value = false;
    }
  });
};

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files;
  console.log(files);
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }
  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  if (suffix != "xlsx") {
    alert("Currently only supports the import of xlsx files");
    return;
  }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson.sheets);
      jsonData.value = exportJson;

      luckysheet.destroy();
      luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
      });
    }
  );
};

// 下载
const downloadDetail = async () => {
  // console.log("下载");
  showTargetPage.value = true;
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false;
  }, 1000);
};
</script>

<template>
  <div class="card">
    <div v-show="!showTargetPage">
      <el-card class="box-card">
        <h1 style="text-align: center">土壤/沉积物 pH分析原始记录</h1>
        <div>SXLPHJ/JL/CX-22-82</div>
        <table class="table">
          <tbody>
            <tr>
              <td colspan="2" style="width: 9%">任务编号</td>
              <td colspan="3">
                <el-input
                  v-model="waterForm.task_name"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="1" style="width: 10%">采样日期</td>
              <td colspan="2">
                {{ sampling_time }}
                <el-input
                  v-model="waterForm.sampling_time"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="1">分析日期</td>
              <td colspan="12">
                <el-input
                  v-model="waterForm.anal_time"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td colspan="2">分析方法</td>
              <td colspan="6">
                <el-input
                  v-model="waterForm.method"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="1">样品类别</td>
              <td colspan="12">
                <el-input
                  v-model="waterForm.category_id"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <Device :water-form="waterForm" :colspan="4" />
            <tr>
              <td colspan="2">温度补偿</td>
              <td colspan="3">
                <el-input
                  v-model="waterForm.temperature_bc"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                >
                  <template #append>
                    <span style="background-color: transparent; color: black">
                      ℃
                    </span>
                  </template>
                </el-input>
              </td>
              <td colspan="1" style="width: 10%">环境温度</td>
              <td colspan="2">
                <el-input
                  v-model="waterForm.temperature"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                >
                  <template #append>
                    <span style="background-color: transparent; color: black">
                      ℃
                    </span>
                  </template>
                </el-input>
              </td>
              <td colspan="1">环境湿度</td>
              <td colspan="12">
                <el-input
                  v-model="waterForm.humidity"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                >
                  <template #append>
                    <span style="background-color: transparent; color: black">
                      %RH
                    </span>
                  </template>
                </el-input>
              </td>
            </tr>
            <tr>
              <td colspan="16" style="text-align: center; font-weight: bold">
                标准缓冲溶液校准
              </td>
            </tr>
            <tr>
              <td colspan="4">标准缓冲溶液理论值</td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.bzhcry.bz_hcyllz1"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.bzhcry.bz_hcyllz2"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.bzhcry.bz_hcyllz3"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td colspan="4">测 定 值</td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.cdz.cdz1"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.cdz.cdz2"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.cdz.cdz3"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
          </tbody>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width: 100%; height: 500px" />
        <table class="table">
          <tbody>
            <tr>
              <td colspan="6">
                <div class="table-td">平行样测定</div>
              </td>
            </tr>
            <tr>
              <td>样品编号</td>
              <td>PH值</td>
              <td>平均值</td>
              <td>差值(PH单位)</td>
              <td>允许差(PH单位)</td>
              <td>是否合格</td>
            </tr>
            <tr>
              <td>
                <el-input
                  v-model="waterForm.pxycd.sampleNumber"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.pxycd.PHValueOne"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.average"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.difference"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.allowed"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.qualified"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td>
                <el-input
                  v-model="waterForm.pxycd.sampleNumberTow"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.pxycd.PHValueTow"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td>
                <el-input
                  v-model="waterForm.pxycd.sampleNumberThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.pxycd.PHValueThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.averageThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.differenceThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.allowedThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td rowspan="2">
                <el-input
                  v-model="waterForm.pxycd.qualifiedThree"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td>
                <el-input
                  v-model="waterForm.pxycd.sampleNumberFour"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.pxycd.PHValueFour"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td colspan="6">
                <div class="table-td">标准样品测定</div>
              </td>
            </tr>
            <tr>
              <td colspan="2">标样批号</td>
              <td colspan="2">测定结果</td>
              <td>标准值</td>
              <td>是否合格</td>
            </tr>
            <tr>
              <td colspan="2">
                <el-input
                  v-model="waterForm.bzycd.byph"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td colspan="2">
                <el-input
                  v-model="waterForm.bzycd.cdjg"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.bzycd.bzz"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
              <td>
                <el-input
                  v-model="waterForm.bzycd.qualified"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
            <tr>
              <td colspan="2">备注</td>
              <td colspan="4">
                <el-input
                  v-model="waterForm.notes"
                  style="width: 100%; border: 1px solid transparent"
                  placeholder="请输入"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </el-card>
    </div>
    <div v-show="showTargetPage">
      <indexPdf
        :waterForm="waterForm"
        :tableHeaders="tableHeaders"
        :tabler="tabler"
      />
    </div>
    <!--    底部公共按钮 (复制粘贴)-->
    <div v-show="!showTargetPage">
      <Index
        :water-form="waterForm"
        :handle-add-water-ph="handleAddWaterPh"
        :download-detail="downloadDetail"
        :check-time="checkTime"
        :switch="false"
        :switch-a-b="switchAB"
        :handle-switch="handleSwitch"
        :get-water-capacity="getWaterCapacity"
        :switch-add="switchAdd"
      />
    </div>

    <!--    提交校核-->
    <el-dialog
      v-model="checkDialogVisible"
      title="提交校核"
      width="30%"
      center
      :before-close="handleCheckClose"
    >
      <div class="check">
        <!--        头部-->
        <div
          class="check-header"
          style="display: flex; align-items: center; margin-bottom: 20px"
        >
          <p>表单填写日期：</p>
          <el-date-picker
            v-model="checkTime"
            style="border: 1px solid #cccccc; border-radius: 6px; width: 70%"
            type="date"
            placeholder="请选择"
          />
        </div>
        <div class="check-footer">
          <el-button style="width: 48%" @click="handleCheckClose">
            取消
          </el-button>
          <el-button type="primary" style="width: 48%" @click="handleSubmit">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
  justify-content: center;
}

/* :deep(.el-input__wrapper) {
  background-color: transparent;
  box-shadow: none;
}
:deep(.el-select__wrapper) {
  background-color: transparent;
  box-shadow: none;
}
:deep(.el-input__wrapper) {
  background-color: transparent;
  box-shadow: none;
} */
::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
